import moment from 'moment'

export function formatMomentObj(moment, format = 'YYYY-MM-DD') {
  return (
    (moment && typeof moment === 'object' && moment.format(format)) || moment
  )
}

export function formatObjMomentValue(obj, key, format = 'YYYY-MM-DD') {
  if (obj) {
    let value = obj[key]
    value && (obj[key] = formatMomentObj(value, format))
  }
}

export function formatObjArrayMomentValue(
  objArray,
  key,
  format = 'YYYY-MM-DD'
) {
  if (objArray && Array.isArray(objArray)) {
    for (const obj of objArray) {
      formatObjMomentValue(obj, key, format)
    }
  }
}

export function formatStr2MomentObj(dateTime, format = 'YYYY-MM-DD') {
  return (
    (dateTime && typeof dateTime === 'string' && moment(dateTime, format)) ||
    dateTime
  )
}

export function formatLv(source, val) {
  const lv =
    source &&
    source.find(e => {
      return e.value === val
    })
  return (lv && lv.label) || val
}

export function formatRes(source, val, keyV = 'code', keyL = 'codeName') {
  const lv =
    source &&
    source.find(e => {
      return e[keyV] === val
    })
  return (lv && lv[keyL]) || val
}

/**
 * 将数组的人民币转换为大写
 * @param n 钱数
 * @returns {string} 转为大写的人民币名称
 *
 * upDigit(168752632)
 * ￥壹亿陆仟捌佰柒拾伍万贰仟陆佰叁拾贰元整"
 *
 * upDigit(-1682)
 * -￥壹仟陆佰捌拾贰元整
 */
export function formatUpDigit(n) {
  let fraction = ['角', '分', '厘']
  let digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  let unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ]
  let head = n < 0 ? '-' : ''
  n = Math.abs(n)
  let s = ''
  for (let i = 0; i < fraction.length; i++) {
    s += (
      digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]
    ).replace(/零./, '')
  }
  s = s || '整'
  n = Math.floor(n)
  for (let i = 0; i < unit[0].length && n > 0; i++) {
    let p = ''
    for (let j = 0; j < unit[1].length && n > 0; j++) {
      p = digit[n % 10] + unit[1][j] + p
      n = Math.floor(n / 10)
    }
    //s = p.replace(/(零.)*零$/, '').replace(/^$/, '零')+ unit[0][i] + s;
    s = p + unit[0][i] + s
  }
  return (
    head +
    s
      .replace(/(零.)*零元/, '元')
      .replace(/(零.)+/g, '零')
      .replace(/^整$/, '零元整')
  )
}
